<template>
    <div>
        <div class="margin-top">
            <el-form :model="formData" :rules="rules" ref="form" label-width="100px">
                <el-form-item label="发文机构" prop="issuing">
                    <el-input v-model="formData.issuing"></el-input>
                </el-form-item>                  
                <el-form-item label="标题" prop="title">
                    <el-input v-model="formData.title"></el-input>
                </el-form-item>
                <el-form-item label="部门" prop="department">
                    <el-autocomplete
                        class="inline-input"
                        v-model="formData.department"
                        :fetch-suggestions="querySearch"
                        placeholder="请输入内容"
                        :trigger-on-focus="false"
                        @select="handleSelect"
                        value-key="name"
                    ></el-autocomplete>
                </el-form-item>
                <el-form-item label="类型" prop="type_id">
                    <el-select v-model="formData.type_id" placeholder="类型">
                        <el-option :label="item.name" :value="item.id" v-for="(item,index) in typelist"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发布时间" prop="issued_date">
                    <el-date-picker type="date" placeholder="选择日期" v-model="formData.issued_date" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
                <el-form-item label="附件" prop="attachment">
                    <el-upload
                        class="upload-demo"
                        :action="$config.uploadUrl"
                        :on-success="handleSuccess"
                        :on-remove="handleRemove"
                        :before-remove="beforeRemove"
                        :data="{token:$user.getToken()}"
                        multiple
                        :limit="3"
                        :on-exceed="handleExceed"
                        :file-list="fileList"
                        list-type="picture">                        
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">描述文字</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <editor v-model="formData.content" ref="editor"/>
                </el-form-item>
                <el-form-item label="权限" prop="permission">
                    <el-checkbox-group v-model="formData.permission">
                        <el-checkbox :label="item.id" v-for="(item,index) in permissionList" :key="'pr_'+index">{{item.name}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('form')">立即创建</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
export default {
    name: "PolicyEdit",
    data() {
        return {
            fileList:[],
            typelist: [],
            permissionList:[],
            formData: {
                id:'',
                title:'',
                content:'',
                issued_date:'',
                department:'',
                type_id:'',
                permission:[],
                attachment:[],
                prefix:'',
                slug:'',
                issuing:'',                                
            },
            rules: {
                title: [
                    { required: true},
                ],
                department: [
                    { required: true},
                ],
                issued_date: [
                    { required: true},
                ],
                type_id: [
                    { required: true},
                ],
                content: [
                    { required: true, message: '请填写'}
                ],
            }
        }
    },
    created() {
        this.formData.id = this.$route.params.id
    },
    mounted() {
        this.getTypeList();
        this.getDetail();
        this.getPermission();
    },
    methods:{
        //上传方法
        handleRemove(file, fileList) {
            let _index = this.fileList.indexOf(file);

            this.formData.attachment.splice(_index,1);
            this.fileList = fileList;
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        handleSuccess(response,files,fileList){
            this.fileList = fileList;

            this.formData.attachment.push(response.data.id);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        getPermission() {
            let _this = this;
            this.$http.httpPost({
                url:'/api/permission',
                datas:{},
                success(res){
                    _this.permissionList = res.data ? res.data : [];
                }
            })
        },
        querySearch(queryString, cb) {
            let _this = this;
            this.$http.httpPost({
                url:'/api/department',
                datas:{name:queryString,current_page:1,pageSize:999},
                success(res){
                    cb(res.data ? res.data : []);
                }
            })
        },
        handleSelect(item) {
            this.formData.department = item.name;
        },
        getDetail(){
            let _this = this;
            this.$http.httpPost({
                url:'/api/policy/show',
                datas:{id:this.formData.id},
                success(res){
                    _this.formData.title = res.title;
                    _this.formData.department = res.department.name;
                    _this.formData.content = res.content;
                    _this.formData.type_id = res.type_id;
                    _this.formData.issued_date = res.issued_date;
                    _this.formData.prefix = res.prefix;
                    _this.formData.slug = res.slug;

                    if (res.issuing) {
                        _this.formData.issuing = res.issuing.name;
                    }

                    let permissionLength = res.permission.length;
                    if(permissionLength > 0){
                        for(let i=0;i < permissionLength;i++){                         
                            _this.formData.permission.push(res.permission[i].permission_id);
                        }
                    }
                    let _att = [];
                    let _fileList = [];
                    let attachmentLength = res.attachment.length;
                    if(attachmentLength > 0){
                        for(let i=0;i < attachmentLength;i++){
                            _att.push(res.attachment[i].attachment_id);
                            _fileList.push({name:res.attachment[i].name,url:res.attachment[i].path});
                        }
                    }

                    _this.formData.attachment = _att;
                    _this.fileList = _fileList;

                    // _this.$refs.editor.html();
                    // _this.$utils.success('创建成功！');
                    // _this.$router.replace({path:'/policy'});
                }
            })
        },
        create() {
            let _this = this;
            this.$http.httpPost({
                url:'/api/policy/update',
                datas:this.formData,
                success(res){
                    console.log(res);
                    _this.postIssuing(res.id);
                    _this.$utils.success('成功！');
                    _this.$router.replace({path:'/policy'});
                }
            })
        },
        postIssuing(id) {
            let _this = this;
            if (_this.formData.issuing) {
                this.$http.httpPost({
                    url:'/api/issuing/store',
                    datas:{
                        "prefix":_this.formData.prefix,
                        "slug":_this.formData.slug,
                        "name":_this.formData.issuing,
                        "data_id":id
                    },
                    success(res){
                        console.log(res);
                        // _this.$utils.success('成功！');
                        // _this.$router.replace({path:'/award'});
                    }
                })    
            }         
        },        
        getTypeList() {
            let _this = this;
            this.$http.httpPost({
                url:'/api/policy/type',
                datas:null,
                success(res){
                    console.log(res);
                    _this.typelist = res.data ? res.data : [];
                }
            })
        },
        submitForm(formName) {
            //存在回调的方法，因为回调外和回调内的作用域不一致，所以务必为 _this 复制 this，否则在回调中无法访问this对象
            let _this = this;
            console.log(this.formData);
            //通过传递form表单ref名称，来调用表单的validate方法
            this.$refs[formName].validate((valid) => {
                //为true时验证通过
                if (valid) {
                    _this.create();
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$utils.message('清空');
            this.$refs[formName].resetFields();
        }
    }
}
</script>
